package com.qianchang.microfinance.view.mine;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;

import com.qianchang.microfinance.R;
import com.qianchang.microfinance.bean.MessageCenterBean;
import com.qianchang.microfinance.bean.PageBean;
import com.qianchang.microfinance.global.DMApplication;
import com.qianchang.microfinance.utils.DMConstant;
import com.qianchang.microfinance.view.base.BaseActivity;
import com.qianchang.microfinance.view.dialog.alert.DimengConfirmAlertDialog;
import com.dm.library.http.DMOKHttpUtils;
import com.dm.library.http.HttpParams;
import com.dm.library.http.base.JsonResult;
import com.dm.library.http.callback.RequestCallBack;
import com.dm.library.utils.DensityUtil;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.DMListView;
import com.dm.library.widgets.DMSwipeRefreshLayout;
import com.dm.library.widgets.element.DTextView;
import com.dm.library.widgets.swipemenulv.SwipeMenu;
import com.dm.library.widgets.swipemenulv.SwipeMenuCreator;
import com.dm.library.widgets.swipemenulv.SwipeMenuItem;
import com.dm.library.widgets.swipemenulv.SwipeMenuListView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 版 权: 深圳市迪蒙网络科技有限公司
 * 描 述:
 * 修 改 人: zhoulai
 * 修改时间: 2017/8/16 13:42
 */


public class MessageListActivity extends BaseActivity {


    @BindView(R.id.message_list_view)
    SwipeMenuListView messageListView;
    @BindView(R.id.swipe_refresh_view)
    DMSwipeRefreshLayout swipeRefreshView;
    @BindView(R.id.tv_right)
    DTextView tvRight;
    private int currentPageIndex = 1;
    private boolean isLoadMore = false;
    private MessageListAdapter messageListAdapter;

    interface DealMessageWay {
        int READ_ONE = 0;
        int DELETE_ONE = 1;
        int READ_ALL = 2;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_message_list);
        ButterKnife.bind(this);

        initView();
        initData();
    }

    @Override
    protected void initView() {
        super.initView();
        setTitleName(getString(R.string.title_my_message));
        messageListAdapter = new MessageListAdapter(this);
        messageListView.setAdapter(messageListAdapter);
        swipeRefreshView.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                getDataFromServer(1);
            }
        });
        messageListView.setOnMoreListener(new DMListView.OnMoreListener() {
            @Override
            public void onLoadMore() {
                isLoadMore = true;
                getDataFromServer(currentPageIndex);
            }
        });

        tvRight.setTextContent(getString(R.string.btn_all_read));
        tvRight.setVisibility(View.GONE);
        messageListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<MessageCenterBean> allMessage = messageListAdapter.getAllMessage();
                if (position >= 0 && position < allMessage.size()) {
                    MessageCenterBean item = messageListAdapter.getItem(position);
                    //未读才去请求服务器修改状态
                    if ("2".equals(item.getNoticeStatus())) {
                        updateStatus(false, false, DealMessageWay.READ_ONE, item);
                    } else {
                        item.setShow(!item.isShow());
                        messageListAdapter.notifyDataSetChanged();
                    }
                }
            }
        });
        initMenuListView();
    }

    @Override
    protected void initData() {
        super.initData();
        show();
        getDataFromServer(1);
    }

    private void getDataFromServer(int pageIndex) {
        HttpParams params = new HttpParams();
        params.put("reqPageNum", pageIndex);
        params.put("maxResults", 10);
//        params.put("receiverId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        params.put("status", "2");
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.FIND_MANAGE_LIST, params, new RequestCallBack<PageBean<MessageCenterBean>>() {
            @Override
            public void onSuccess(JsonResult<PageBean<MessageCenterBean>> response) {
                if (response.isReqDataSuccess()) {
                    PageBean<MessageCenterBean> pageResultBean = response.getObject();
                    dismiss();
                    swipeRefreshView.setRefreshing(false);
                    if (pageResultBean != null) {
                        List<MessageCenterBean> info = pageResultBean.getList();
                        if (isLoadMore) {
                            messageListAdapter.addAll(info);
                        } else {
                            currentPageIndex = 1;
                            if (pageResultBean.getList().size() == 0) {
                                messageListView.hasEmptyData();
                            } else {
                                messageListAdapter.updateAll(info);
                            }
                        }
                        messageListView.hasMoreDate(pageResultBean.isHasNextPage());
                    }
                    currentPageIndex++;
                } else {
                    ToastUtil.getInstant().show(MessageListActivity.this, response.getDescription());
                }

                if (messageListAdapter != null) {
                    if (messageListAdapter.getAllMessage().size() > 0) {
                        tvRight.setVisibility(View.VISIBLE);
                    } else {
                        tvRight.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                swipeRefreshView.setRefreshing(false);
                ToastUtil.getInstant().show(MessageListActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }

    @OnClick(R.id.tv_right)
    public void onViewClicked() {
        DimengConfirmAlertDialog confirmAlertDialog = DimengConfirmAlertDialog.newInstance("", getString(R.string.set_all_read));
        confirmAlertDialog.setOnDialogClickListener(new DimengConfirmAlertDialog.OnDialogClickListener() {
            @Override
            public void agree() {
                updateStatus(true, false, DealMessageWay.READ_ALL, null);
            }

            @Override
            public void cancel() {

            }
        });
        confirmAlertDialog.setAgreeText(getString(R.string.confirm));
        confirmAlertDialog.show(getSupportFragmentManager(), getClass().getSimpleName());

    }

    /**
     * 1已读
     * 2未读
     * 3删除
     */
    private void updateStatus(boolean isAll, boolean isDelete, final int flag, final MessageCenterBean item) {
        show();
        HttpParams params = new HttpParams();
        if (!isAll) {
            params.put("ids", item.getId());
        } else {
            params.put("receiverId", DMApplication.getInstance().getmUserLoginInfo().getUserId());
        }
        if (isDelete) {
            params.put("noticeStatus", "3");
        } else {
            params.put("noticeStatus", "1");
        }
        DMOKHttpUtils.getInstance().post(this, DMConstant.ApiURL.UPDATE_NOTICE_STATUS, params, new RequestCallBack<String>() {

            @Override
            public void onSuccess(JsonResult<String> response) {
                dismiss();
                if (response.isReqDataSuccess()) {
                    switch (flag) {
                        case MessageListActivity.DealMessageWay.READ_ONE:
                            if (!"1".equals(item.getNoticeStatus())) {
                                item.setNoticeStatus("1");
                            }
                            item.setShow(!item.isShow());
                            messageListAdapter.notifyDataSetChanged();
                            break;
                        case MessageListActivity.DealMessageWay.DELETE_ONE:
                            List<MessageCenterBean> allMessage = messageListAdapter.getAllMessage();
                            allMessage.remove(item);
                            messageListAdapter.notifyDataSetChanged();
                            break;
                        case MessageListActivity.DealMessageWay.READ_ALL:
                            if (messageListAdapter != null) {
                                if (messageListAdapter.getAllMessage().size() > 0) {
                                    messageListAdapter.readAll();
                                }
                            }
                            break;
                    }
                } else {
                    ToastUtil.getInstant().show(MessageListActivity.this, response.getDescription());
                }

                if (messageListAdapter != null) {
                    if (messageListAdapter.getAllMessage().size() > 0) {
                        tvRight.setVisibility(View.VISIBLE);
                    } else {
                        tvRight.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            public void onFailure(String msg) {
                dismiss();
                ToastUtil.getInstant().show(MessageListActivity.this, msg);
            }

            @Override
            public void onConnectFailure(String msg) {

            }
        });
    }


    private void initMenuListView() {
        //创建一个SwipeMenuCreator供ListView使用
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                //创建一个侧滑菜单
                SwipeMenuItem openItem = new SwipeMenuItem(getApplicationContext());
                //给该侧滑菜单设置背景
                //                openItem.setBackground(new ColorDrawable(Color.rgb(0xFF, 0x00, 0x00)));
                openItem.setBackground(new ColorDrawable(getResources().getColor(R.color.common_red_color)));
                //设置宽度
                openItem.setWidth(DensityUtil.dip2px(MessageListActivity.this, 55));
                //设置名称
                openItem.setTitle(getString(R.string.delete));
                //字体大小
                openItem.setTitleSize(14);
                //字体颜色
                openItem.setTitleColor(Color.WHITE);
                //加入到侧滑菜单中
                menu.addMenuItem(openItem);
            }
        };

        messageListView.setMenuCreator(creator);

        //侧滑菜单的相应事件
        messageListView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {

                if (messageListAdapter != null) {
                    MessageCenterBean item = messageListAdapter.getItem(position);
                    updateStatus(false, true, DealMessageWay.DELETE_ONE, item);
                }

                return false;
            }
        });
    }

}
